"""
Example usage script for Rehabilitation Assessment System

This script demonstrates how to:
1. Build a template from expert video
2. Evaluate a patient video
3. Generate reports
"""

import os
import yaml
import logging

# Configure logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

print("=" * 60)
print("康复动作评估系统 - 使用示例")
print("=" * 60)
print()


def example_build_template():
    """Example: Build a template from expert video."""
    print("示例 1: 构建专家动作模板")
    print("-" * 60)

    from src.utils.template_builder import TemplateBuilder

    # Load configuration
    with open('config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # Initialize template builder
    builder = TemplateBuilder(
        templates_dir=config['paths']['templates'],
        config=config
    )

    # Note: You need to provide an actual expert video file
    expert_video_path = './templates/squat/down.mp4'

    if not os.path.exists(expert_video_path):
        print(f"⚠️  请先准备专家演示视频: {expert_video_path}")
        print("   跳过此示例...")
        print()
        return

    # Build template
    print(f"正在处理视频: {expert_video_path}")
    template = builder.build_template(
        video_path=expert_video_path,
        action_type='squat',
        template_name='expert',
        metadata={
            'description': '蹲下标准动作',
            'difficulty': 2
        }
    )

    print(f"✓ 模板构建完成!")
    print(f"  - 元数据: {template['meta_path']}")
    print(f"  - 特征文件: {template['features_path']}")
    print(f"  - 关键点文件: {template['landmarks_path']}")
    print()


def example_evaluate_video():
    """Example: Evaluate a patient video."""
    print("示例 2: 评估患者视频")
    print("-" * 60)

    from src.core.pose_detector import PoseDetector
    from src.core.skeleton_normalizer import SkeletonNormalizer
    from src.core.feature_extractor import FeatureExtractor
    from src.core.action_segmenter import ActionSegmenter
    from src.core.matcher import ActionMatcher
    from src.core.report_generator import ReportGenerator
    from src.utils.template_builder import TemplateBuilder

    # Load configuration
    with open('config.yaml', 'r') as f:
        config = yaml.safe_load(f)

    # 使用专家视频作为测试
    patient_video_path = './templates/squat/down.mp4'  # 临时使用专家视频测试

    if not os.path.exists(patient_video_path):
        print(f"⚠️  请先准备患者视频: {patient_video_path}")
        print("   跳过此示例...")
        print()
        return

    print(f"正在评估视频: {patient_video_path}")
    print("(注意: 临时使用专家视频作为患者视频进行测试)")
    print()
    print()

    # Initialize components
    print("1. 初始化组件...")
    pose_detector = PoseDetector(
        model_complexity=config['pose_detection']['model_complexity']
    )
    skeleton_normalizer = SkeletonNormalizer(
        canvas_size=tuple(config['skeleton']['canvas_size'])
    )
    feature_extractor = FeatureExtractor(
        device=config['feature_extraction']['device']
    )
    action_segmenter = ActionSegmenter(
        window_size=config['segmentation']['window_size'],
        threshold_multiplier=config['segmentation']['threshold_multiplier'],
        min_action_length=config['segmentation']['min_action_length'],
        max_action_length=config['segmentation']['max_action_length']
    )
    action_matcher = ActionMatcher()
    report_generator = ReportGenerator()
    template_builder = TemplateBuilder(config=config)

    # Process video
    print("2. 检测姿态...")
    landmarks_seq, metadata = pose_detector.detect_from_video(patient_video_path)
    landmarks_seq = pose_detector.interpolate_missing_frames(landmarks_seq)

    print("3. 归一化和渲染骨架...")
    normalized_seq, rendered_imgs = skeleton_normalizer.process_sequence(landmarks_seq)

    print("4. 提取深度特征...")
    patient_features = feature_extractor.extract_from_sequence(rendered_imgs)

    print("5. 切分动作并检测阶段...")
    segments_with_phases = action_segmenter.segment_with_phases(
        normalized_seq,
        fps=metadata.get('fps', 30.0),
        action_type='squat'
    )
    print(f"   检测到 {len(segments_with_phases)} 个动作段（包含阶段信息）")

    for i, seg in enumerate(segments_with_phases):
        print(f"   动作段 {i+1}: 帧{seg['start']}-{seg['end']}, "
              f"下蹲阶段: {seg['phases']['squat_down']}, "
              f"起立阶段: {seg['phases']['squat_up']}")

    # Load template and score
    print("6. 加载模板并评分（混合评估：整体+阶段）...")
    action_type = 'squat'

    try:
        template = template_builder.load_template(action_type)

        # Extract template phases if available
        template_phases = template.get('phases', None)

        # Add squat-specific phases to template if it has generic phases
        if template_phases and 'peak' in template_phases:
            template_peak = template_phases['peak']
            template_start = 0
            template_end = template['num_frames']
            template_phases['squat_down'] = (template_start, template_peak)
            template_phases['squat_up'] = (template_peak, template_end)

        results = []
        for i, segment_info in enumerate(segments_with_phases):
            start = segment_info['start']
            end = segment_info['end']
            patient_phases = segment_info['phases']

            print(f"   评分动作段 {i+1}/{len(segments_with_phases)}...")

            # Overall segment score
            overall_score = action_matcher.compute_comprehensive_score(
                patient_features[start:end],
                template['features'],
                normalized_seq[start:end],
                template['landmarks']
            )

            # Phase-specific scores (if template has phase info)
            phase_scores = {}
            if template_phases:
                phase_scores = action_matcher.compute_phase_scores(
                    patient_features,
                    template['features'],
                    normalized_seq,
                    template['landmarks'],
                    patient_phases,
                    template_phases
                )

            # Combine results - flatten scores for report generator compatibility
            result = {
                'action_type': action_type,
                'frame_range': [int(start), int(end)],
                **overall_score,  # Flatten scores dict to top level
                'phase_scores': phase_scores,
                'phases': patient_phases
            }
            results.append(result)

        # Generate report
        print("7. 生成评估报告...")
        session_id = 'demo_session'
        report_paths = report_generator.generate_full_report(
            session_id,
            results,
            metadata={'video_path': patient_video_path}
        )

        print()
        print("✓ 评估完成!")
        if len(results) > 0:
            # Calculate overall average score
            avg_score = sum(r['final_score'] for r in results) / len(results)
            print(f"  - 总体评分: {avg_score:.2f}")
            print(f"  - 动作段数: {len(results)}")

            # Display phase-specific scores if available
            for i, r in enumerate(results):
                print(f"\n  动作段 {i+1}:")
                print(f"    整体得分: {r['final_score']:.2f}")
                if r.get('phase_scores'):
                    if r['phase_scores'].get('squat_down'):
                        down_score = r['phase_scores']['squat_down']['final_score']
                        print(f"    下蹲阶段得分: {down_score:.2f}")
                    if r['phase_scores'].get('squat_up'):
                        up_score = r['phase_scores']['squat_up']['final_score']
                        print(f"    起立阶段得分: {up_score:.2f}")
        else:
            print(f"  - 总体评分: N/A (未检测到动作段)")
        print(f"  - JSON 报告: {report_paths.get('json', 'N/A')}")
        print(f"  - HTML 报告: {report_paths.get('html', 'N/A')}")

        if len(results) == 0:
            print()
            print("⚠️  建议: 调整动作分割参数以检测更多动作段")
            print("   编辑 config.yaml:")
            print("     segmentation:")
            print("       threshold_multiplier: 0.8  # 从1.5降低")
            print("       min_action_length: 10      # 从15降低")
        print()

    except Exception as e:
        print(f"⚠️  无法加载模板 '{action_type}': {e}")
        print("   请先构建模板（参见示例 1）")
        print()


def example_api_usage():
    """Example: Use REST API."""
    print("示例 3: 使用 REST API")
    print("-" * 60)

    print("启动 API 服务器:")
    print("  $ python src/api/app.py")
    print()
    print("或使用快速启动脚本:")
    print("  $ ./start.sh")
    print()
    print("API 端点:")
    print()
    print("1. 健康检查:")
    print("   GET http://localhost:5000/health")
    print()
    print("2. 评估视频:")
    print('   POST http://localhost:5000/api/evaluate')
    print('   Body: {')
    print('     "video_path": "patients/patient_001.mp4",')
    print('     "action_type": "raise_leg_left",')
    print('     "session_id": "patient_001"')
    print('   }')
    print()
    print("3. 列出模板:")
    print("   GET http://localhost:5000/api/templates")
    print()
    print("4. 获取报告:")
    print("   GET http://localhost:5000/api/report/<session_id>?format=html")
    print()


def main():
    """Run all examples."""

    # Example 1: Build template
    example_build_template()

    # Example 2: Evaluate video
    example_evaluate_video()

    # Example 3: API usage
    # example_api_usage()

    print("=" * 60)
    print("更多信息请参阅 README.md")
    print("=" * 60)


if __name__ == '__main__':
    main()
